# coding=utf-8
"""Tweet items"""

from datetime import timedelta, datetime
from mitems.tools.utils import post_to_twitter, TWITTER_MAX_LENGTH, TwitterError
from django.conf import settings
from mitems.tools.logs import Log
from mitems.models import Item

log = Log(settings.TWITTER_LOG_FILE, settings.TWITTER_LOG_LOGGER,
          settings.TWITTER_LOG_SIZE,settings.TWITTER_LOG_COUNT, settings.DEBUG)
TWITTER_MESSAGE_MAX_LENGTH = TWITTER_MAX_LENGTH - 22

ITEMS = Item.objects.filter(slumped=False,
                            time_expired__gte=(datetime.now()+timedelta(minutes=settings.TWITTER_MINUTES_TO_LIVE)),
                            twitter_sent=False, created_by__twitter_allow=True)


def tweet_items():
    """Tweet"""
    log.log('Start tweet items', 'info')
    for item in ITEMS:
        message = item.message
        if len(message) > TWITTER_MESSAGE_MAX_LENGTH:
            size = len(message + '...') - TWITTER_MESSAGE_MAX_LENGTH
            message = u'%s...' % message[:-size]
        short_url = item.get_short_url()
        message = '%s - %s' % (message, short_url)
        try:
            post_to_twitter(message,
                            settings.TWITTER_PUBLIC_USER_TOKEN,
                            settings.TWITTER_PUBLIC_USER_TOKEN_SECRET
            )
            log.log('Item %s has been posted to twitter successfully'%short_url, 'info')
        except TwitterError as error:
            log.log('Cannot tweet %s item: %s'%(short_url, error), 'error')
            pass
        item.twitter_sent = True
        item.save()

if __name__ == '__main__':
    tweet_items()